import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xvideos/tools_base/file_upload/file_upload_tool.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/LoadingHelper.dart';
import 'package:xvideos/hj_utils/api_service/comment_service.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';

import '../../../../../../hj_utils/global.dart';
import '../../../../hj_model/message/message_bean.dart';
import '../../../../hj_model/mine/base_list_res.dart';
import '../../../zaixiankefu/chat_widget/chat_page/List_component/ListComponentPage.dart';
import '../chat_page.dart';

class ChatLogic extends GetxController {
  /* Controllers */
  late final ScrollController scrollController = ScrollController();
  late final TextEditingController textEditingController = TextEditingController();
  late final FocusNode focusNode = FocusNode();
  bool? isShowLoadWidget;

  bool isLoading = true;

  Future<void> onFieldSubmitted() async {
    if (!isTextFieldEnable) return;

    LoadingHelper.showLoading();
    scrollController.animateTo(
      0,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
    sendMsg(content: textEditingController.text);
    textEditingController.text = '';
    update();
  }

  void onFieldChanged(String term) {
    update();
  }

  /* Getters */
  bool get isTextFieldEnable => textEditingController.text.isNotEmpty;

  RefreshController? refreshController;
  List<MessageBean> list = [];
  int pageNumber = 1;
  String? sessionId;
  late int uid;
  var userName = "".obs;
  bool isGoodsInfo = false;

  // String? goodsId;
  // GoodsInfo? goodsInfo;
  // ChatGoods? info;
  // ShopWishDetailModel? wishModal;
  // int? objType = 0; //物品类型. 1 原味商店-商品; 2 原味商店-许愿单
  static goToChatPage(
      {required int uid,
      String? sessionId,
      String? userName,
      String? goodsId,
      // GoodsInfo? info,
      // ShopWishDetailModel? wishModal,
      int? objType}) {
    bool isVip = globalStore.meInfo?.isVip ?? false;
    bool isStoreOwner = globalStore.meInfo?.isStoreOwner ?? false;
    if (objType == 1 || objType == 3) {
      if (!isVip) {
        showToast('私信只对会员开放！');
        return;
      }
      if (isStoreOwner) {
        showToast('店主不能联系卖家！');
        return;
      }
    }
    return Get.to(() => MyChatPage(), arguments: {
      'uid': uid,
      'sessionId': sessionId,
      'userName': userName,
      'goodsId': goodsId,
      'objType': objType,
    });
  }

  @override
  void onInit() {
    super.onInit();
    isShowLoadWidget = true;
    uid = Get.arguments?["uid"];
    sessionId = Get.arguments?['sessionId'];
    userName.value = Get.arguments?['userName'] ?? "";
  }

  @override
  void onReady() {
    super.onReady();
    if (sessionId == null) {
      MineService.getSessionId(uid: uid).then((value) {
        sessionId = value;
        if (sessionId != null) {
          loadData();
        }
      });
    } else if (sessionId != null) {
      loadData();
    }
  }

  bool haveMoreData = true;
  void loadData() async {
    BaseListResEntity<MessageBean>? entity =
        await (MineService.getChatMessage(sessionId: sessionId!, pageSize: 20, pageNumber: pageNumber));

    if (entity != null && entity.list != null && entity.list!.isNotEmpty) {
      list.addAll(entity.list!);
      if (userName.isEmpty) {
        userName.value = list[0].takeName ?? "";
      }
    }
    if(entity?.hasNext == false){
      haveMoreData = false;
    }
    isLoading = false;

    refreshController?.loadComplete(); 

    update();
  }

  void sendMsg({List<String>? imgUrl, String? content}) async {
    focusNode.unfocus();
    bool result = await CommentService.sendMessage(
      takeUid: uid,
      imgUrl: imgUrl,
      content: content,
    );
    if (result) {
      list.clear();
      loadData();
    }
    LoadingHelper.dismissLoading();
  }

  Future<void> onUpPic(File compressedFile) async {
    LoadingHelper.showLoading();
    var picUrl = await FileUpLoadTool().uploadImage(compressedFile.path, callback: (total, progress) {});
    if (picUrl?.coverImg == null) {
      LoadingHelper.dismissLoading();
    } else if (picUrl?.coverImg != null) {
      sendMsg(imgUrl: [picUrl!.coverImg!]);
    }
  }

  void onRefresh() {
    pageNumber = 1;
    loadData();
  }

  void onLoadingMore() {
    pageNumber += 1;
    loadData();
  }

  final List<String> textList = ['相册', '拍照', '取消'];

  void showBottomSheet(context) {
    showModalBottomSheet(
        isScrollControlled: true,
        context: context,
        builder: (context) => SafeArea(
              child: SizedBox(
                height: 180,
                child: ListView(
                    children: List.generate(
                  textList.length,
                  (index) => InkWell(
                      child: Container(alignment: Alignment.center, height: 60.0, child: Text(textList[index])),
                      onTap: () {
                        if (index == 0) {
                          getImageByGallery();
                        } else if (index == 1) {
                          getImageByCamera();
                        } else if (index == 2) {}
                        Navigator.pop(context);
                      }),
                )),
              ),
            ));
  }

  Future getImageByGallery() async {
    var image = await ImagePicker().pickImage(source: ImageSource.gallery);
    var tw = 400;
    XFile? _image = image;
    ImageProperties properties = await FlutterNativeImage.getImageProperties(_image!.path);
    File compressedFile = await FlutterNativeImage.compressImage(_image.path,
        quality: 80,
        // percentage: 100,
        targetWidth: tw,
        targetHeight: (properties.height! * tw / (properties.width!)).round());

    //拍照获取图片上传
    onUpPic(compressedFile);
  }

  Future getImageByCamera() async {
    var image = await ImagePicker().pickImage(source: ImageSource.camera);
    XFile? _image = image;
    var tw = 400;
    ImageProperties properties = await FlutterNativeImage.getImageProperties(_image!.path);
    File compressedFile = await FlutterNativeImage.compressImage(_image.path,
        quality: 80, targetWidth: tw, targetHeight: (properties.height! * tw / properties.width!).round());

    //拍照获取图片上传
    onUpPic(compressedFile);
  }

  void savePicture(String url) async {
    var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
    await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
  }
}
